package vow.gui;

import jade.core.Agent;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ComboBoxModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.Group;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.LayoutStyle.ComponentPlacement;

import agents.TheWatcher;
import javax.swing.DefaultComboBoxModel;

import ontology.models.contract.ActionP;
import ontology.models.contract.Fact;

import vow.gui.models.StringListModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JSplitPane;

public class VOMemberActions extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JPanel actionArgsPanel = new JPanel();
	private GroupLayout gl_actionArgsPanel;
	private String sender;
	private String cid;
	private List<String> receivers;
	private Set<String> actions;
	private TheWatcher agent;
	private JComboBox receiversBox;
	private JComboBox actionsBox;
	private List<Slot> argsSlots;
	private JLabel lblWarningMessage;

	/**
	 * Create the dialog.
	 */
	public VOMemberActions(TheWatcherGUI parent) {
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}
	
	
	public String getCid() {
		return cid;
	}


	public void setCid(String cid) {
		this.cid = cid;
	}

	

	public TheWatcher getAgent() {
		return agent;
	}


	public void setAgent(TheWatcher myAgent) {
		this.agent = myAgent;
	}


	public List<String> getReceivers() {
		return receivers;
	}

	public void setReceivers(List<String> receivers) {
		this.receivers = receivers;
	}

	public Set<String> getActions() {
		return actions;
	}

	public void setActions(Set<String> actions) {
		this.actions = actions;
	}

	public String getSender() {
		return sender;
	}

	public void setSender(String sender) {
		this.sender = sender;
	}
	
	public void launchActionsDialog(){
		initComponents();
		lblWarningMessage.setText("Fill all the fields");
		handleSelectedAction();
		setVisible(true);
	}

	
	private void handleSelectedAction(){
		String selected = (String) actionsBox.getSelectedItem();
		Pattern p = Pattern.compile("[A-z0-9]+");
		Matcher m = p.matcher(selected);
		ArrayList<String> args = new ArrayList<String>();
		boolean found = m.find();
		while(found){
			args.add(m.group());
			found = m.find();
		}
		List<String> list = args.subList(1, args.size());
		argsSlots = new ArrayList<Slot>();
		for(String arg : list){
			argsSlots.add(new Slot(arg));
		}
		EventQueue.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				drawArgsSlots();
			}
		});
	}
	
	private void drawArgsSlots(){
		gl_actionArgsPanel = new GroupLayout(actionArgsPanel);
		actionArgsPanel.setLayout(gl_actionArgsPanel);
		gl_actionArgsPanel.setAutoCreateGaps(true);
		gl_actionArgsPanel.setAutoCreateContainerGaps(true);
		   GroupLayout.SequentialGroup hGroup = gl_actionArgsPanel.createSequentialGroup();
		   Group hg1 = gl_actionArgsPanel.createParallelGroup();
		   Group hg2 = gl_actionArgsPanel.createParallelGroup();
		   for(Slot s : argsSlots){
			   hg1 = hg1.addComponent(s.getLabel());
			   hg2 = hg2.addComponent(s);
		   }
		   hGroup.addGroup(hg1);
		   hGroup.addGroup(hg2);
		   gl_actionArgsPanel.setHorizontalGroup(hGroup);
		   GroupLayout.SequentialGroup vGroup = gl_actionArgsPanel.createSequentialGroup();
		   for(Slot s : argsSlots){
			   vGroup.addGroup(gl_actionArgsPanel.createParallelGroup(Alignment.BASELINE).
			            addComponent(s.getLabel()).addComponent(s));
		   }
		   gl_actionArgsPanel.setVerticalGroup(vGroup);
	}
	
	private void initComponents(){
		setBounds(100, 100, 448, 171);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		
		JSplitPane splitPane = new JSplitPane();
		GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
		gl_contentPanel.setHorizontalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_contentPanel.createSequentialGroup()
					.addComponent(splitPane, GroupLayout.PREFERRED_SIZE, 422, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		gl_contentPanel.setVerticalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addComponent(splitPane, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		
		JPanel panel_1 = new JPanel();
		splitPane.setLeftComponent(panel_1);
		
		JLabel lblAco = new JLabel("Ac\u00E7\u00E3o");
		
		actionsBox = new JComboBox();
		actionsBox.setModel(new DefaultComboBoxModel(actions.toArray()));
		actionsBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				handleSelectedAction();	
			}
		});
		JLabel lblDestinatrio = new JLabel("Destinat\u00E1rio");
		
		receiversBox = new JComboBox();
		receiversBox.setModel(new DefaultComboBoxModel(receivers.toArray()));
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addComponent(lblAco)
						.addComponent(lblDestinatrio))
					.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING, false)
						.addComponent(receiversBox, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(actionsBox, 0, 75, Short.MAX_VALUE))
					.addContainerGap())
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_panel_1.createSequentialGroup()
					.addContainerGap(37, Short.MAX_VALUE)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblAco)
						.addComponent(actionsBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(receiversBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblDestinatrio))
					.addContainerGap())
		);
		panel_1.setLayout(gl_panel_1);
		
		splitPane.setRightComponent(actionArgsPanel);
		gl_actionArgsPanel = new GroupLayout(actionArgsPanel);
		gl_actionArgsPanel.setHorizontalGroup(
			gl_actionArgsPanel.createParallelGroup(Alignment.LEADING)
				.addGap(0, 258, Short.MAX_VALUE)
		);
		gl_actionArgsPanel.setVerticalGroup(
			gl_actionArgsPanel.createParallelGroup(Alignment.LEADING)
				.addGap(0, 88, Short.MAX_VALUE)
		);
		actionArgsPanel.setLayout(gl_actionArgsPanel);
		contentPanel.setLayout(gl_contentPanel);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						performAction(e);
					}
				});
				
				lblWarningMessage = new JLabel("");
				buttonPane.add(lblWarningMessage);
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}
	
	private String buildActionStatement(String action) throws Exception{
		boolean fieldEmpty = false;
		for(int i = 0; i < argsSlots.size() && !fieldEmpty; i++){
			String argument = argsSlots.get(i).getText();
			if(argument.isEmpty())
				fieldEmpty = true;
			else {
				action = action.replaceAll(argsSlots.get(i).getArgument(), argsSlots.get(i).getText());
			}
		}
		if(fieldEmpty)
			throw new Exception("All the fields must be filled");
		return action;
	}
	
	private void performAction(ActionEvent e){
		long now = System.currentTimeMillis();
		Fact facto = new Fact();
		ActionP action = new ActionP();
		try {
			action.setName(buildActionStatement((String)actionsBox.getSelectedItem()));
			action.setSender(sender);
			action.setReceiver((String)receiversBox.getSelectedItem());
			action.setTicker(""+now);
			facto.setAction(action);
			facto.setWhen(now+"");
			facto.setContractId(cid);
			agent.performAction(facto);
			dispose();
		} catch (Exception e1) {
			lblWarningMessage.setText(e1.getMessage());
			e1.printStackTrace();
		}
	}
	
	public class Slot extends JTextField{
		private String argument;
		private JLabel label;
		
		public Slot(String argument){
			super(10);
			label = new JLabel(argument);
			this.argument = argument;
		}

		public String getArgument() {
			return argument;
		}

		public void setArgument(String argument) {
			this.argument = argument;
		}

		public JLabel getLabel() {
			return label;
		}

		public void setLabel(JLabel label) {
			this.label = label;
		}
	}
}
